package com.py.framework.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.entity.DictDetailEntity;
import com.py.framework.entity.DictEntity;
import com.py.framework.service.SysDictService;

/**
 * 字典管理Controller
 * @author Leegern
 * @date   2018年4月20日
 */
@RestController
@RequestMapping("/sysdict")
public class SysDictController extends SystemController {
	
	@Autowired
	private SysDictService sysDictService;
	
	
	/**
	 * @api {post} /sysdict/addDict.json 添加字典信息
	 * @apiName addDict
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {DictEntity}  entity 字典实体
	 * @apiParam {String} dictName 字典名称
	 * @apiParam {String} dictKey 字典KEY值
	 * @apiParam {String} enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {"dictName":"批次反馈类型","dictKey":"PCFK","enabled":2}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/addDict", method = RequestMethod.POST)
	public RestServiceResult<Object> addDict(@RequestBody DictEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			List<DictEntity> dicList=sysDictService.fineSameDict(entity.getDictKey());
			if(dicList.size()>1) {
				result = super.getFailedRestServiceResult("添加的字典KEY重复！");
				ExceptionLogger.error("sysdict#addDict","添加失败");
			}else {
				try {
					sysDictService.addDict(entity);
				} catch (Exception e) {
					result = super.getFailedRestServiceResult("添加失败！");
					ExceptionLogger.error(e);
				}
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/queryDictListForPage.json 分页查询字典信息
	 * @apiName queryDictListForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {String}  dictKey 标识码
	 * @apiParam {String}  dictName 字典名称
	 * @apiParam {int}  page  当前页码
	 * @apiParam {int}  limit 每页条数
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dictName 字典名称
	 * @apiSuccess {String} dictKey 字典KEY值
	 * @apiSuccess {String} enabled 是否使用，1否，2是
	 * @apiSuccess {String} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":[{"id":1,"createTime":"2018-07-10 11:11:11","delFlag":1,"dictName":"批次反馈类型","dictKey":"PCFK","enabled":2}]}
	 */
	@RequestMapping(value = "/queryDictListForPage.json", method = RequestMethod.POST)
	public RestServiceResult<List<DictEntity>> queryDictListForPage(String dictKey, String dictName, int page, int limit) {
		Page pager = super.getPage(page, limit);
		// 分页查询字典信息
		List<DictEntity> datas = sysDictService.queryDictListForPage(dictKey, dictName, pager);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}
	
	/**
	 * @api {post} /sysdict/fineOneDict.json 根据Id查询字典数据
	 * @apiName fineOneDict
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {long}  id 字典Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	* @apiSuccess {String} dictName 字典名称
	 * @apiSuccess {String} dictKey 字典KEY值
	 * @apiSuccess {String} enabled 是否使用，1否，2是
	 * @apiSuccess {String} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":{"id":1,"createTime":"2018-07-10 11:11:11","delFlag":1,"dictName":"批次反馈类型","dictKey":"PCFK","enabled":2}}
	 */
	@RequestMapping(value = "/fineOneDict", method = RequestMethod.POST)
	public RestServiceResult<DictEntity> fineOneDict(long id) {
		DictEntity data = null;
		if (id > Constants.NUMBER_ZERO) {
			// 根据Id查询字典数据
			data = sysDictService.fineOneDict(id);
		}
		return super.getSuccessRestServiceResult(data);
	}
	
	/**
	 * @api {post} /sysdict/updateDict.json 更新字典信息
	 * @apiName updateDict
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {DictEntity} entity 字典实体
	 * @apiParam {long} id 字典ID
	 * @apiParam {String} dictName 字典名称
	 * @apiParam {String} dictKey 字典KEY值
	 * @apiParam {String} enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateDict", method = RequestMethod.POST)
	public RestServiceResult<Object> updateDict(@RequestBody DictEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				sysDictService.updateDict(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/updateDictStatus.json 批量更新字典数据状态
	 * @apiName updateDictStatus
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {long}  id 字典Id
	 * @apiParam {int}  enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateDictStatus", method = RequestMethod.POST)
	public RestServiceResult<Object> updateDictStatus(long id, int enabled) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (id > Constants.NUMBER_ZERO && enabled > Constants.NUMBER_ZERO) {
			try {
				// 批量更新字典数据状态
				sysDictService.batchUpdateDictStatus(Arrays.asList(id), enabled, Constants.NUMBER_ZERO);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/batchDelDict.json 批量删除字典数据
	 * @apiName batchDelDict
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {String}  ids 字典Id集合
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/batchDelDict", method = RequestMethod.POST)
	public RestServiceResult<Object> batchDelDict(String ids) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(ids)) {
			try {
				// 批量删除字典数据
				sysDictService.batchUpdateDictStatus(super.convert2Long(ids), Constants.NUMBER_ZERO, Constants.NUMBER_TWO);
			} catch (ServiceException e) {
				result = super.getFailedRestServiceResult(e.getMessage());
				ExceptionLogger.error(e);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("删除失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	
	/**
	 * @api {post} /sysdict/addDictDetail.json 添加字典明细信息
	 * @apiName addDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {DictDetailEntity}  entity 字典明细实体
	 * @apiParam {String} dtlKey KEY值
	 * @apiParam {String} dtlValue 字典值
	 * @apiParam {int} orderBy 排序
	 * @apiParam {int} enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {"dtlKey":"SEL_KEY","dtlValue":"22","orderBy":1,"enabled":1}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/addDictDetail", method = RequestMethod.POST)
	public RestServiceResult<Object> addDictDetail(@RequestBody DictDetailEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				sysDictService.addDictDetail(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/queryDictDetailListForPage.json 分页查询字典明细信息
	 * @apiName queryDictDetailListForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {int}  page  当前页码
	 * @apiParam {int}  limit 每页条数
	 * @apiParam {String}  dtlKey 字典KEY
	 * @apiParam {String}  dtlValue 字典值
	 * @apiParam {long}  dictId 字典Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String}  dtlKey 字典KEY
	 * @apiSuccess {String}  dtlValue 字典值
	 * @apiSuccess {long}  dictId 字典Id
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":[{"id":1,"createTime":"2018-07-10 11:11:11","dtlValue":"222","dtlKey":"PCFK","enabled":2}]}
	 */
	@RequestMapping(value = "/queryDictDetailListForPage", method = RequestMethod.POST)
	public RestServiceResult<List<DictDetailEntity>> queryDictDetailListForPage(int page, int limit, String dtlKey, String dtlValue,
								@RequestParam(value="dictId",required=true,defaultValue="0")long dictId) {
		Map<String, Object> params = new HashMap<>();
		Page pager = super.getPage(page, limit);
		params.put("page", pager);
		params.put("dictId", dictId);
		params.put("dtlKey", dtlKey);
		params.put("dtlValue", dtlValue);
		// 分页查询字典明细信息
		List<DictDetailEntity> datas = sysDictService.queryDictDetailListForPage(params);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}
	
	/**
	 * @api {post} /sysdict/fineOneDictDetail.json 根据Id查询字典明细
	 * @apiName fineOneDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {long}  id 字典明细Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String}  dtlKey 字典KEY
	 * @apiSuccess {String}  dtlValue 字典值
	 * @apiSuccess {long}  dictId 字典Id
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":{"id":1,"createTime":"2018-07-10 11:11:11","dtlValue":"222","dtlKey":"PCFK","enabled":2}}
	 */
	@RequestMapping(value = "/fineOneDictDetail", method = RequestMethod.POST)
	public RestServiceResult<DictDetailEntity> fineOneDictDetail(long id) {
		DictDetailEntity data = null;
		if (id > Constants.NUMBER_ZERO) {
			// 根据Id查询字典明细
			data = sysDictService.fineOneDictDetail(id);
		}
		return super.getSuccessRestServiceResult(data);
	}
	
	/**
	 * @api {post} /sysdict/updateDictDetailStatus.json 批量更新字典明细数据状态
	 * @apiName updateDictDetailStatus
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {long}  id 字典明细Id
	 * @apiParam {int}  enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateDictDetailStatus", method = RequestMethod.POST)
	public RestServiceResult<Object> updateDictDetailStatus(long id, int enabled) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (id > Constants.NUMBER_ZERO && enabled > Constants.NUMBER_ZERO) {
			try {
				// 批量更新字典明细数据状态
				sysDictService.batchUpdateDictDetailStatus(Arrays.asList(id), enabled, Constants.NUMBER_ZERO);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/batchDelDictDetail.json 批量删除字典明细数据
	 * @apiName batchDelDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {String}  ids 字典明细Id集合
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/batchDelDictDetail", method = RequestMethod.POST)
	public RestServiceResult<Object> batchDelDictDetail(String ids) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(ids)) {
			try {
				// 批量删除字典明细数据
				sysDictService.batchUpdateDictDetailStatus(super.convert2Long(ids), Constants.NUMBER_ZERO, Constants.NUMBER_TWO);
			} catch (ServiceException e) {
				result = super.getFailedRestServiceResult(e.getMessage());
				ExceptionLogger.error(e);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("删除失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/updateDictDetail.json 更新字典明细信息
	 * @apiName updateDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {DictDetailEntity}  entity 字典明细实体
	 * @apiParam {String} dtlKey KEY值
	 * @apiParam {String} dtlValue 字典值
	 * @apiParam {int} orderBy 排序
	 * @apiParam {int} enabled 是否使用，1否，2是
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateDictDetail", method = RequestMethod.POST)
	public RestServiceResult<Object> updateDictDetail(@RequestBody DictDetailEntity entity) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				sysDictService.updateDictDetail(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /sysdict/isExistDictDetail.json 根据字典明细键判断是否有重复数据
	 * @apiName isExistDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 字典管理 
	 * @apiParam {String}  dtlKey 明细键
	 * @apiParam {long}  dictId 字典Id
	 * @apiParam {long}  dictDetailId 字典明细Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag  true 存在重复, false 不存在重复
	 * @apiSuccessExample {json} 成功返回结果
	 *    {"code":0,"msg":null,"count":0,"data":{"flag":"true"}}
	 */
	@RequestMapping(value = "/isExistDictDetail", method = RequestMethod.POST)
	public RestServiceResult<Map<String, String>> isExistDictDetail(String dtlKey, long dictId,
			@RequestParam(value="dictId", required=false, defaultValue="0") long dictDetailId) {
		RestServiceResult<Map<String, String>> rstData = null;
		Map<String, String> result = new HashMap<>();
		String flag = "";
		if (StringUtils.isNotBlank(dtlKey) && dictId > Constants.NUMBER_ZERO) {
			try {
				List<DictDetailEntity> datas = sysDictService.getDictDetailByKey(dictId, dictDetailId, dtlKey);
				if (! CollectionUtils.isEmpty(datas)) {
					flag = "true";
				} else {
					flag = "false";
				}
				result.put("flag", flag);
			} catch (Exception e) {
				rstData = super.getFailedRestServiceResult("查询失败！");
				ExceptionLogger.error(e);
			}
		}
		rstData = super.getSuccessRestServiceResult(result);
		return rstData;
	}
	
	/**
	 * 获取指定字典详情值
	 *
	 * @param dictKey
	 *            字典值
	 * @return RestServiceResult
	 * @author YaoS
	 * @date 10:07 18/11/9
	 **/
	@RequestMapping(value = "/getDictDetails", method = RequestMethod.POST)
	public RestServiceResult<List<DictDetailEntity>> getDictDetails(
			@RequestParam(value = "dictKey", defaultValue = "", required = true) String dictKey,
			HttpServletRequest request) {
		RestServiceResult<List<DictDetailEntity>> result = new RestServiceResult<>();
		try {
			List<DictDetailEntity> list = sysDictService.getDictDetails(dictKey, StringUtils.EMPTY);
			result.setData(list);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取字典详情值失败！");
			return result;
		}
		return result;
	}
}